<template>
  <t-form-item v-show="!data.hidden" :label="data.label" :name="data.key">
    <component
      :is="componentsMap[data.type]"
      v-if="!data.slot"
      v-model="formValue[data.key]"
      :item="data"
      :disabled="data.disabled"
      v-bind="$attrs"
    ></component>
    <slot v-else :name="data.key"></slot>
  </t-form-item>
</template>

<script setup lang="ts">
import { markRaw, ref, watch } from 'vue';

const props = defineProps({
  data: {
    type: Object as any,
    default: () => {
      return {};
    },
  },
  formData: {
    type: Object as any,
    default: () => {
      return {};
    },
  },
});

const fileModules = import.meta.glob('./widgets/**/*.vue', { eager: true });
const componentsMap = ref<any>({});
const formValue = ref<any>({});

const getComponentMap = () => {
  for (const key in fileModules) {
    const item: any = fileModules[key];
    const pathStr = key
      .split('/')
      .find((item) => item.indexOf('.vue') !== -1)
      .split('.')
      .find((item) => item.indexOf('View') !== -1);

    if (item?.default) componentsMap.value[pathStr] = markRaw(item.default);
  }
};

getComponentMap();

watch(
  () => props.formData,
  (data: any) => {
    formValue.value = data;
  },
  { immediate: true, deep: true },
);
</script>

<style lang="less" scoped></style>
